package pack.findthewords;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.content.res.Configuration;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

public class Answer extends Activity {
    int lvl=0;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	super.onCreate(savedInstanceState);
	setContentView(R.layout.answer);

	// On small screens, force portrait layout
	if (((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_SMALL)
	    || ((getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) == Configuration.SCREENLAYOUT_SIZE_NORMAL)) {
	    setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
	}

	// Try to get LVL from Bundle
	try {
	    getBundle(savedInstanceState);
	}
	catch (Exception e) {
	    lvl=getIntent().getExtras().getInt(Utils.LEVELTAG);
	}
	fillPage();

	final TextView tipTv=(TextView) findViewById(R.id.ans_tip);
	int r=Utils.getRandForTip();
	final String urlTip=Utils.LOOKUP_TIPS_URLS[r];
	tipTv.setText(getResources().getString(Utils.LOOKUP_TIPS[r]));
	tipTv.setOnClickListener(new View.OnClickListener() {
	    @Override
	    public void onClick(View v) {
		Intent i=new Intent(Intent.ACTION_VIEW, Uri.parse(urlTip));
		startActivity(i);
	    }
	});

    }

    private void getBundle(Bundle savedInstanceState) {
	lvl=savedInstanceState.getInt(Utils.LVL_BUNDLE_LABEL);
    }

    private boolean checkAnswerOk() {
	String correctB=getResources().getString(Utils.LOOKUP_B[lvl]).toUpperCase();
	String correctD=getResources().getString(Utils.LOOKUP_D[lvl]).toUpperCase();
	String correctF=getResources().getString(Utils.LOOKUP_F[lvl]).toUpperCase();
	EditText editB=(EditText) findViewById(R.id.editText_b);
	String answeredB=editB.getEditableText().toString().trim().toUpperCase();
	EditText editD=(EditText) findViewById(R.id.editText_d);
	String answeredD=editD.getEditableText().toString().trim().toUpperCase();
	EditText editF=(EditText) findViewById(R.id.editText_f);
	String answeredF=editF.getEditableText().toString().trim().toUpperCase();
	if ( ! correctF.equals(Utils.NULLCHAR.toUpperCase())) {
	    if (answeredB.equals(correctB) && answeredD.equals(correctD) && answeredF.equals(correctF)) {
		return true;
	    }
	}
	else {
	    if (answeredB.equals(correctB) && answeredD.equals(correctD)) {
		return true;
	    }
	}
	return false;
    }

    private void gotToNext() {
	lvl++;
	fillPage();
    }

    private void gotToPrev() {
	lvl--;
	fillPage();
    }

    private void fillPage() {
	// Checks
	SharedPreferences settings=getSharedPreferences(Utils.PREFS_NAME, 0);
	Boolean solved=settings.getBoolean("lvl" + lvl, false);
	String e=getResources().getString(Utils.LOOKUP_E[lvl]);

	// Fill text fields
	TextView tvA=(TextView) findViewById(R.id.ans_a);
	tvA.setText(getResources().getString(Utils.LOOKUP_A[lvl]));

	EditText editB=(EditText) findViewById(R.id.editText_b);
	TextView tvB=(TextView) findViewById(R.id.ans_b);
	if (solved) {
	    tvB.setText(getResources().getString(Utils.LOOKUP_B[lvl]).toUpperCase());
	    tvB.setVisibility(View.VISIBLE);
	    editB.setVisibility(View.GONE);
	}
	else {
	    editB.setHint(getResources().getString(Utils.LOOKUP_B[lvl]).substring(0, 1).toUpperCase() + Utils.TRAILS);
	    editB.setText("");
	    editB.setVisibility(View.VISIBLE);
	    tvB.setVisibility(View.GONE);
	    editB.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
		    int scale=(int) getResources().getDisplayMetrics().density;
		    if (hasFocus) {
			findViewById(R.id.ans_bottom_hr).setVisibility(View.GONE);
			findViewById(R.id.ans_tip).setVisibility(View.GONE);
			findViewById(R.id.ans_bottom_img).setVisibility(View.GONE);
			findViewById(R.id.ans_scroll).setPadding(Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale,
			    Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale);
		    }
		    else {
			findViewById(R.id.ans_bottom_hr).setVisibility(View.VISIBLE);
			findViewById(R.id.ans_tip).setVisibility(View.VISIBLE);
			findViewById(R.id.ans_bottom_img).setVisibility(View.VISIBLE);
			findViewById(R.id.ans_scroll).setPadding(Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale,
			    Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale);
		    }
		}
	    });
	}

	TextView tvC=(TextView) findViewById(R.id.ans_c);
	tvC.setText(getResources().getString(Utils.LOOKUP_C[lvl]));

	EditText editD=(EditText) findViewById(R.id.editText_d);
	TextView tvD=(TextView) findViewById(R.id.ans_d);
	if (solved) {
	    tvD.setText(getResources().getString(Utils.LOOKUP_D[lvl]).toUpperCase());
	    tvD.setVisibility(View.VISIBLE);
	    editD.setVisibility(View.GONE);
	}
	else {
	    editD.setHint(getResources().getString(Utils.LOOKUP_D[lvl]).substring(0, 1).toUpperCase() + Utils.TRAILS);
	    editD.setText("");
	    editD.setVisibility(View.VISIBLE);
	    tvD.setVisibility(View.GONE);
	    editD.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		@Override
		public void onFocusChange(View v, boolean hasFocus) {
		    int scale=(int) getResources().getDisplayMetrics().density;
		    if (hasFocus) {
			findViewById(R.id.ans_bottom_hr).setVisibility(View.GONE);
			findViewById(R.id.ans_tip).setVisibility(View.GONE);
			findViewById(R.id.ans_bottom_img).setVisibility(View.GONE);
			findViewById(R.id.ans_scroll).setPadding(Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale,
			    Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale);
		    }
		    else {
			findViewById(R.id.ans_bottom_hr).setVisibility(View.VISIBLE);
			findViewById(R.id.ans_tip).setVisibility(View.VISIBLE);
			findViewById(R.id.ans_bottom_img).setVisibility(View.VISIBLE);
			findViewById(R.id.ans_scroll).setPadding(Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale,
			    Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale);
		    }
		}
	    });
	}

	if ( ! e.equals(Utils.NULLCHAR)) {
	    TextView tvE=(TextView) findViewById(R.id.ans_e);
	    tvE.setText(getResources().getString(Utils.LOOKUP_E[lvl]));
	    tvE.setVisibility(View.VISIBLE);

	    EditText editF=(EditText) findViewById(R.id.editText_f);
	    TextView tvF=(TextView) findViewById(R.id.ans_f);
	    if (solved) {
		tvF.setText(getResources().getString(Utils.LOOKUP_F[lvl]).toUpperCase());
		tvF.setVisibility(View.VISIBLE);
		editF.setVisibility(View.GONE);
	    }
	    else {
		editF.setHint(getResources().getString(Utils.LOOKUP_F[lvl]).substring(0, 1).toUpperCase()
		    + Utils.TRAILS);
		editF.setText("");
		editF.setVisibility(View.VISIBLE);
		tvF.setVisibility(View.GONE);
		editF.setOnFocusChangeListener(new View.OnFocusChangeListener() {
		    @Override
		    public void onFocusChange(View v, boolean hasFocus) {
			int scale=(int) getResources().getDisplayMetrics().density;
			if (hasFocus) {
			    findViewById(R.id.ans_bottom_hr).setVisibility(View.GONE);
			    findViewById(R.id.ans_tip).setVisibility(View.GONE);
			    findViewById(R.id.ans_bottom_img).setVisibility(View.GONE);
			    findViewById(R.id.ans_scroll).setPadding(Utils.ANS_PADDING * scale, 0,
				Utils.ANS_PADDING * scale, 0);
			}
			else {
			    findViewById(R.id.ans_bottom_hr).setVisibility(View.VISIBLE);
			    findViewById(R.id.ans_tip).setVisibility(View.VISIBLE);
			    findViewById(R.id.ans_bottom_img).setVisibility(View.VISIBLE);
			    findViewById(R.id.ans_scroll).setPadding(Utils.ANS_PADDING * scale,
				Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale, Utils.ANS_PADDING * scale);
			}
		    }
		});
	    }
	}
	else {
	    // Hide last 2 fields
	    TextView tvE=(TextView) findViewById(R.id.ans_e);
	    EditText editF=(EditText) findViewById(R.id.editText_f);
	    TextView tvF=(TextView) findViewById(R.id.ans_f);
	    tvE.setVisibility(View.GONE);
	    editF.setVisibility(View.GONE);
	    tvF.setVisibility(View.GONE);
	}
	// Set listeners
	final Button answerButton=(Button) findViewById(R.id.ans_btn_ans);
	if ( ! solved) {
	    answerButton.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
		    if (checkAnswerOk()) {
			correctAnswSeq();
		    }
		    else {
			Toast
			    .makeText(Answer.this, getResources().getString(R.string.answer_wrong), Toast.LENGTH_SHORT)
			    .show();
		    }
		}
	    });
	    answerButton.setClickable(Boolean.TRUE);
	    answerButton.setTextColor(getResources().getColorStateList(R.drawable.btn_selector));
	}
	else {
	    answerButton.setClickable(Boolean.FALSE);
	    answerButton.setTextColor(Color.LTGRAY);
	}

	final Button nextButton=(Button) findViewById(R.id.ans_btn_next);
	if (lvl < (Utils.LOOKUP_A.length - 1)) {
	    nextButton.setOnClickListener(new View.OnClickListener() {
		@Override
		public void onClick(View v) {
		    gotToNext();
		    /*
		     * Toast.makeText(Answer.this, getResources().getString(R.string.toast_lvl) +
		     * " " + (lvl + 1), Toast.LENGTH_SHORT).show();
		     */
		}
	    });
	    nextButton.setClickable(Boolean.TRUE);
	    nextButton.setTextColor(getResources().getColorStateList(R.drawable.btn_selector));
	}
	else {
	    nextButton.setClickable(Boolean.FALSE);
	    nextButton.setTextColor(Color.LTGRAY);
	}

	final Button prevButton=(Button) findViewById(R.id.ans_btn_prev);
	if (lvl > 0) {
	    prevButton.setOnClickListener(new OnClickListener() {
		@Override
		public void onClick(View v) {
		    gotToPrev();
		    /*
		     * Toast.makeText(Answer.this, getResources().getString(R.string.toast_lvl) +
		     * " " + (lvl + 1), Toast.LENGTH_SHORT).show();
		     */
		}
	    });
	    prevButton.setClickable(Boolean.TRUE);
	    prevButton.setTextColor(getResources().getColorStateList(R.drawable.btn_selector));
	}
	else {
	    prevButton.setClickable(Boolean.FALSE);
	    prevButton.setTextColor(Color.LTGRAY);
	}
    }

    private void correctAnswSeq() {
	SharedPreferences settings=getSharedPreferences(Utils.PREFS_NAME, 0);
	SharedPreferences.Editor editor=settings.edit();
	editor.putBoolean("lvl" + lvl, true);
	editor.commit();
	//
	RelativeLayout ll=(RelativeLayout) findViewById(R.id.ans_global_ll);
	Animation fadeOut=AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_out);
	ll.startAnimation(fadeOut);
	fillPage();
	Animation fadeIn=AnimationUtils.loadAnimation(getApplicationContext(), android.R.anim.fade_in);
	ll.startAnimation(fadeIn);

	// Check progress
	int recount=0;
	for (int i=0; i < Utils.LOOKUP_A.length; i++) {
	    if (settings.getBoolean("lvl" + i, false)) {
		recount++;
	    }
	}
	if (recount == Utils.LOOKUP_A.length) {
	    // Game completed
	    AlertDialog alertDialog=new AlertDialog.Builder(Answer.this).create();
	    alertDialog.setIcon(android.R.drawable.ic_dialog_info);
	    alertDialog.setTitle(getResources().getString(R.string.gz_title));
	    alertDialog.setMessage(getResources().getString(R.string.gz_all));
	    alertDialog.setButton((getResources().getString(android.R.string.ok)),
		new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			dialog.cancel();
		    }
		});
	    alertDialog.setButton2((getResources().getString(R.string.gz_share)),
		new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			Uri imageUri=Uri.parse("android.resource://pack.findthewords/drawable/share");
			Intent i=new Intent(Intent.ACTION_SEND);
			i.setType("text/plain");
			i.putExtra(Intent.EXTRA_TITLE, getResources().getString(R.string.gz_title_2));
			i.putExtra(Intent.EXTRA_TEXT, getText(R.string.gz_msg_all));
			startActivity(Intent.createChooser(i, getText(R.string.gz_title_2)));
		    }
		});
	    alertDialog.show();
	}
	else if ((recount % Utils.SMALL_STEP) == 0) {
	    // 5x Ditloids completed
	    final int rec_util=recount;
	    AlertDialog alertDialog=new AlertDialog.Builder(Answer.this).create();
	    alertDialog.setIcon(android.R.drawable.ic_dialog_info);
	    alertDialog.setTitle(getResources().getString(R.string.gz_title));
	    alertDialog.setMessage(getResources().getString(R.string.gz_progress_1) + " " + recount + " "
		+ getResources().getString(R.string.gz_progress_2) + " " + Utils.LOOKUP_A.length + "!");
	    alertDialog.setButton((getResources().getString(android.R.string.ok)),
		new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			dialog.cancel();
		    }
		});
	    alertDialog.setButton2((getResources().getString(R.string.gz_share)),
		new DialogInterface.OnClickListener() {
		    @Override
		    public void onClick(DialogInterface dialog, int which) {
			Intent i=new Intent(Intent.ACTION_SEND);
			i.setType("text/plain");
			i.putExtra(Intent.EXTRA_TITLE, getResources().getString(R.string.gz_title_2));
			i.putExtra(Intent.EXTRA_TEXT, getResources().getString(R.string.gz_msg_1) + " " + rec_util
			    + " " + getResources().getString(R.string.gz_msg_2));
			startActivity(Intent.createChooser(i, getText(R.string.gz_title_2)));
		    }
		});
	    alertDialog.show();

	}
	else {
	    Toast.makeText(Answer.this, getResources().getString(R.string.answer_correct), Toast.LENGTH_SHORT).show();
	}
    }

    @Override
    public void onSaveInstanceState(Bundle savedInstanceState) {
	savedInstanceState.putInt(Utils.LVL_BUNDLE_LABEL, lvl);
	super.onSaveInstanceState(savedInstanceState);
    }

    @Override
    public void onRestoreInstanceState(Bundle savedInstanceState) {
	super.onRestoreInstanceState(savedInstanceState);
	getBundle(savedInstanceState);
    }

    /*
     * Options menu
     */
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
	MenuInflater inflater=getMenuInflater();
	inflater.inflate(R.menu.opt_menu_gen, menu);
	return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
	switch (item.getItemId()) {
	    case R.id.opt_vote:
		Intent ii=new Intent(Intent.ACTION_VIEW, Uri.parse(Utils.MARKET_URL));
		startActivity(ii);
		return true;
	    case R.id.opt_back:
		finish();
		return true;
		/*
		 * case R.id.opt_adfree: Intent iii=new Intent(Intent.ACTION_VIEW,
		 * Uri.parse(Utils.MARKET_URL_NOADS)); startActivity(iii); return true; case
		 * R.id.opt_info: Intent iiii=new Intent(Answer.this, Info.class);
		 * startActivity(iiii); return true;
		 */
	    default:
		return super.onOptionsItemSelected(item);
	}
    }
}
